package br.com.unip.visao;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import br.com.unip.modelo.Departamento;
import br.com.unip.persistencia.DepartamentoDao;

public class AppDepartamentoNovoGui extends JFrame implements ActionListener {
	private static final long serialVersionUID = 1L;
	private JDialog dialogFunc;
	private JPanel panelDepto;
	private JLabel labelDepNome, labelDepCodGer;
	private JTextField textDepNome, textDepCodGer;
	private JButton btnDepSalvar, btnDepCancelar;

	public AppDepartamentoNovoGui() {
		super("Projeto UNIP - SWING - ALPOO - Novo departamento");
		
		labelDepNome = new JLabel("Nome:");
		labelDepCodGer = new JLabel("Código do gerente:");

		textDepNome = new JTextField(50);
		textDepCodGer = new JTextField(50);

		btnDepSalvar = new JButton("Salvar");
		btnDepCancelar = new JButton("Cancelar");

		btnDepSalvar.addActionListener(this);
		btnDepCancelar.addActionListener(this);

		panelDepto = new JPanel();
		panelDepto.setLayout(new GridLayout(6, 2));
		panelDepto.setBorder(BorderFactory.createTitledBorder("Dados"));
		panelDepto.add(labelDepNome);
		panelDepto.add(textDepNome);
		panelDepto.add(labelDepCodGer);
		panelDepto.add(textDepCodGer);
		panelDepto.add(btnDepSalvar);
		panelDepto.add(btnDepCancelar);
		
		dialogFunc = new JDialog();
		dialogFunc.add(panelDepto);
		
		dialogFunc.setResizable(false);
		dialogFunc.setSize(650, 200);
		dialogFunc.setLocationRelativeTo(null);
		dialogFunc.setModal(true);
		dialogFunc.setVisible(true);
	}

	public void actionPerformed(ActionEvent ae) {
		Object evento = ae.getSource();
		if (evento == btnDepSalvar) {
			System.out.println("Ação => Salvando");
			try {
				Departamento d = new Departamento();
				DepartamentoDao dd = new DepartamentoDao();
				d.setNome(textDepNome.getText());
				d.setCod_ger(Integer.parseInt(textDepCodGer.getText()));
				dd.gravar(d);
				textDepNome.setText("");
				textDepCodGer.setText("");
				JOptionPane.showMessageDialog(null,
						"Registro salvo com sucesso!", "Sucesso",
						JOptionPane.INFORMATION_MESSAGE);
				
				// Gambiarra que tem que ser arrumada! o.O (sem net para pesquisar)
				AppListGui.paneLista.setSelectedIndex(1);
				AppListGui.paneLista.setSelectedIndex(2);
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, "Erro : " + e.getMessage(),
						"Atenção!", JOptionPane.ERROR_MESSAGE);
			}
		}
		if (evento == btnDepCancelar) {
			System.out.println("Ação => Cancelando");
			dialogFunc.dispose();
		}
	}
}
